<template>
  <div class="exception-statistics">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>异常订单统计分析</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>导出报表
        </el-button>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待处理异常</span>
              <el-tag type="warning">{{ statistics.pendingCount }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="['trend-value', statistics.pendingTrend > 0 ? 'up' : 'down']">
                {{ Math.abs(statistics.pendingTrend) }}%
                <el-icon>
                  <component :is="statistics.pendingTrend > 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
            <div class="detail">
              <div class="detail-item">
                <span class="label">紧急</span>
                <span class="value">{{ statistics.urgentCount }}</span>
              </div>
              <div class="detail-item">
                <span class="label">普通</span>
                <span class="value">{{ statistics.normalCount }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日新增</span>
              <el-tag type="info">{{ statistics.todayNewCount }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较昨日</span>
              <span :class="['trend-value', statistics.newTrend > 0 ? 'up' : 'down']">
                {{ Math.abs(statistics.newTrend) }}%
                <el-icon>
                  <component :is="statistics.newTrend > 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
            <div class="detail">
              <div class="detail-item">
                <span class="label">退款纠纷</span>
                <span class="value">{{ statistics.refundCount }}</span>
              </div>
              <div class="detail-item">
                <span class="label">服务投诉</span>
                <span class="value">{{ statistics.complaintCount }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均处理时长</span>
              <el-tag type="success">{{ statistics.avgProcessTime }}小时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较上周</span>
              <span :class="['trend-value', statistics.processTimeTrend < 0 ? 'up' : 'down']">
                {{ Math.abs(statistics.processTimeTrend) }}%
                <el-icon>
                  <component :is="statistics.processTimeTrend < 0 ? 'ArrowDown' : 'ArrowUp'" />
                </el-icon>
              </span>
            </div>
            <div class="detail">
              <div class="detail-item">
                <span class="label">最快</span>
                <span class="value">{{ statistics.minProcessTime }}小时</span>
              </div>
              <div class="detail-item">
                <span class="label">最慢</span>
                <span class="value">{{ statistics.maxProcessTime }}小时</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>满意度评分</span>
              <el-tag type="primary">{{ statistics.satisfactionScore }}分</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="trend">
              <span>较上周</span>
              <span :class="['trend-value', statistics.satisfactionTrend > 0 ? 'up' : 'down']">
                {{ Math.abs(statistics.satisfactionTrend) }}%
                <el-icon>
                  <component :is="statistics.satisfactionTrend > 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
            <div class="detail">
              <div class="detail-item">
                <span class="label">好评率</span>
                <span class="value">{{ statistics.goodRate }}%</span>
              </div>
              <div class="detail-item">
                <span class="label">差评率</span>
                <span class="value">{{ statistics.badRate }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>异常订单趋势</span>
              <el-radio-group v-model="trendType" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="trendChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>异常类型分布</span>
              <el-select v-model="distributionType" size="small">
                <el-option label="按类型" value="type" />
                <el-option label="按处理方式" value="process" />
                <el-option label="按处理结果" value="result" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" ref="distributionChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-section">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>处理效率分析</span>
              <el-select v-model="efficiencyType" size="small">
                <el-option label="平均处理时长" value="time" />
                <el-option label="处理及时率" value="rate" />
                <el-option label="一次解决率" value="first" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" ref="efficiencyChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>处理人员绩效</span>
              <el-select v-model="performanceType" size="small">
                <el-option label="处理数量" value="count" />
                <el-option label="平均时长" value="time" />
                <el-option label="满意度" value="satisfaction" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" ref="performanceChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="data-table">
      <template #header>
        <div class="card-header">
          <span>异常订单明细</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索订单号/客户名称"
              clearable
              style="width: 200px"
              @input="handleSearch"
            />
            <el-select v-model="filterStatus" placeholder="处理状态" clearable @change="handleSearch">
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已完成" value="completed" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="orderNo" label="订单号" min-width="150" />
        <el-table-column prop="customerName" label="客户名称" width="120" />
        <el-table-column prop="type" label="异常类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.type)">
              {{ getExceptionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handler" label="处理人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="processTime" label="处理时长" width="120">
          <template #default="{ row }">
            {{ row.processTime }}小时
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="satisfaction" label="满意度" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.satisfaction"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getMerchantOrderExceptionStatistics,
  getMerchantOrderExceptionTrend,
  getMerchantOrderExceptionDistribution,
  getMerchantOrderExceptionEfficiency,
  getMerchantOrderExceptionPerformance,
  getMerchantOrderExceptionList,
  exportMerchantOrderExceptionReport
} from '@/api/merchant'

// 日期范围选择
const dateRange = ref([])
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 统计数据
const statistics = reactive({
  pendingCount: 0,
  pendingTrend: 0,
  urgentCount: 0,
  normalCount: 0,
  todayNewCount: 0,
  newTrend: 0,
  refundCount: 0,
  complaintCount: 0,
  avgProcessTime: 0,
  processTimeTrend: 0,
  minProcessTime: 0,
  maxProcessTime: 0,
  satisfactionScore: 0,
  satisfactionTrend: 0,
  goodRate: 0,
  badRate: 0
})

// 图表相关
const trendType = ref('day')
const distributionType = ref('type')
const efficiencyType = ref('time')
const performanceType = ref('count')
const trendChartRef = ref(null)
const distributionChartRef = ref(null)
const efficiencyChartRef = ref(null)
const performanceChartRef = ref(null)
let trendChart = null
let distributionChart = null
let efficiencyChart = null
let performanceChart = null

// 表格相关
const loading = ref(false)
const searchKeyword = ref('')
const filterStatus = ref('')
const tableData = ref([])
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantOrderExceptionStatistics({
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    })
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 初始化趋势图表
const initTrendChart = async () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  const { data } = await getMerchantOrderExceptionTrend({
    type: trendType.value,
    startDate: dateRange.value[0],
    endDate: dateRange.value[1]
  })
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['新增异常', '处理完成', '待处理']
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增异常',
        type: 'line',
        data: data.newCounts
      },
      {
        name: '处理完成',
        type: 'line',
        data: data.completedCounts
      },
      {
        name: '待处理',
        type: 'line',
        data: data.pendingCounts
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化分布图表
const initDistributionChart = async () => {
  if (!distributionChartRef.value) return
  
  distributionChart = echarts.init(distributionChartRef.value)
  const { data } = await getMerchantOrderExceptionDistribution({
    type: distributionType.value,
    startDate: dateRange.value[0],
    endDate: dateRange.value[1]
  })
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: data.map(item => ({
          name: item.name,
          value: item.value
        }))
      }
    ]
  }
  
  distributionChart.setOption(option)
}

// 初始化效率图表
const initEfficiencyChart = async () => {
  if (!efficiencyChartRef.value) return
  
  efficiencyChart = echarts.init(efficiencyChartRef.value)
  const { data } = await getMerchantOrderExceptionEfficiency({
    type: efficiencyType.value,
    startDate: dateRange.value[0],
    endDate: dateRange.value[1]
  })
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        type: 'bar',
        data: data.values
      }
    ]
  }
  
  efficiencyChart.setOption(option)
}

// 初始化绩效图表
const initPerformanceChart = async () => {
  if (!performanceChartRef.value) return
  
  performanceChart = echarts.init(performanceChartRef.value)
  const { data } = await getMerchantOrderExceptionPerformance({
    type: performanceType.value,
    startDate: dateRange.value[0],
    endDate: dateRange.value[1]
  })
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: data.handlers
    },
    series: [
      {
        type: 'bar',
        data: data.values
      }
    ]
  }
  
  performanceChart.setOption(option)
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderExceptionList({
      keyword: searchKeyword.value,
      status: filterStatus.value,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
      page: page.current,
      size: page.size
    })
    tableData.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取表格数据失败:', error)
    ElMessage.error('获取表格数据失败')
  } finally {
    loading.value = false
  }
}

// 导出报表
const handleExport = async () => {
  try {
    await exportMerchantOrderExceptionReport({
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    })
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出报表失败:', error)
    ElMessage.error('导出报表失败')
  }
}

// 查看详情
const handleViewDetail = (row) => {
  // TODO: 实现查看详情功能
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getTableData()
}

// 日期变化
const handleDateChange = () => {
  getStatistics()
  initTrendChart()
  initDistributionChart()
  initEfficiencyChart()
  initPerformanceChart()
  getTableData()
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getTableData()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getTableData()
}

// 获取异常类型标签类型
const getExceptionTypeTag = (type) => {
  const typeMap = {
    refund: 'danger',
    complaint: 'warning',
    product: 'error',
    other: 'info'
  }
  return typeMap[type] || ''
}

// 获取异常类型标签文本
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    refund: '退款纠纷',
    complaint: '服务投诉',
    product: '商品问题',
    other: '其他异常'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return statusMap[status] || ''
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return statusMap[status] || status
}

// 监听图表类型变化
watch([trendType, distributionType, efficiencyType, performanceType], () => {
  initTrendChart()
  initDistributionChart()
  initEfficiencyChart()
  initPerformanceChart()
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
  trendChart?.resize()
  distributionChart?.resize()
  efficiencyChart?.resize()
  performanceChart?.resize()
})

onMounted(() => {
  // 设置默认日期范围为最近一个月
  dateRange.value = dateShortcuts[1].value()
  
  // 初始化数据
  getStatistics()
  getTableData()
  
  // 初始化图表
  nextTick(() => {
    initTrendChart()
    initDistributionChart()
    initEfficiencyChart()
    initPerformanceChart()
  })
})
</script>

<style lang="scss" scoped>
.exception-statistics {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .data-overview {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      .trend {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        color: #666;
        font-size: 14px;

        .trend-value {
          display: flex;
          align-items: center;
          gap: 4px;

          &.up {
            color: #f56c6c;
          }

          &.down {
            color: #67c23a;
          }
        }
      }

      .detail {
        display: flex;
        justify-content: space-between;

        .detail-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 4px;

          .label {
            color: #666;
            font-size: 12px;
          }

          .value {
            font-size: 16px;
            font-weight: 500;
          }
        }
      }
    }
  }

  .chart-section {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .data-table {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        gap: 10px;
      }
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 